package com.huxiu.yd;

import android.content.Intent;
import android.os.Bundle;
import android.text.format.DateUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.model.Action;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.model.SpareItem;
import com.huxiu.yd.net.model.User;
import com.huxiu.yd.net.responses.ActionListResponse;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.net.responses.SpareListResponse;
import com.huxiu.yd.utils.Constants;
import com.huxiu.yd.utils.ErrorResponseException;
import com.huxiu.yd.utils.ImageUtils;
import com.huxiu.yd.utils.LogUtils;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.DiscoveryViewHolder;
import com.huxiu.yd.view.SpareItemViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.nostra13.universalimageloader.core.ImageLoader;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by yao on 15/8/27:上午8:54.
 */
public class UserProfileActivity extends BaseActivity implements OnClickListener,
        OnCheckedChangeListener, OnRefreshListener2<ListView> {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    private String userId;

    private int currentActionPage = 0;

    private int currentSparePage = 0;

    private int currentMassivePage = 0;

    private User user;

    private String avatar;

    private String username;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);
        userId = getIntent().getStringExtra(Constants.USER_ID_KEY);
        if (userId.equals("0")) {
            finish();
            return;
        }
        avatar = getIntent().getStringExtra("avatar");
        username = getIntent().getStringExtra("username");
        ButterKnife.setDebug(true);
        ButterKnife.inject(this);
        rightText.setVisibility(View.GONE);
        rightImage.setVisibility(View.GONE);
        title.setText("Ta的个人主页");
        back.setOnClickListener(this);
        View headerView = getLayoutInflater()
                .inflate(R.layout.user_profile_header_view, list.getRefreshableView(), false);
        headerViewHolder = new UserProfileHeaderViewHolder(headerView);
        headerViewHolder.privateMsg.setOnClickListener(this);
        headerViewHolder.attentions.setOnClickListener(this);
        headerViewHolder.massiveTest.setOnClickListener(this);
        headerViewHolder.spare.setOnClickListener(this);
        list.getRefreshableView().addHeaderView(headerView);
        spareAdapter = new SpareAdapter();
        massiveTestAdapter = new MassiveTestAdapter();
        actionAdapter = new ActionAdapter();
        lastCheckedId = R.id.attentions;
        headerViewHolder.attentions.setSelected(true);
        list.setAdapter(actionAdapter);
        list.setOnRefreshListener(this);
        list.setState(State.INIT_REFRESHING, true);
        bindUserInfo();
    }

    private UserProfileHeaderViewHolder headerViewHolder;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.private_msg:
                if (Settings.isLoggedIn()) {
                    Intent intent = new Intent(this, ChatActivity.class);
                    intent.putExtra(ChatActivity.EXTRA_UID, userId);
                    intent.putExtra(ChatActivity.EXTRA_NAME, username);
                    intent.putExtra(ChatActivity.EXTRA_AVATAR, avatar);
                    startActivity(intent);
                } else {
                    Utils.askLogIn(this);
                }
                break;
            case R.id.attentions:
            case R.id.spare:
            case R.id.massive_test:
                headerViewHolder.spare.setSelected(false);
                headerViewHolder.attentions.setSelected(false);
                headerViewHolder.massiveTest.setSelected(false);
                v.setSelected(true);
                onCheckedChanged(null, v.getId());
                break;
            default:
                break;
        }
    }

    private int lastCheckedId;

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        LogUtils.d("OnCheckedChanged, checkedId is " + checkedId + ", lastCheckedId is "
                + lastCheckedId);
        if (checkedId == lastCheckedId) {
            return;
        }
        lastCheckedId = checkedId;
        switch (checkedId) {
            case R.id.attentions:
                list.setAdapter(actionAdapter);
                break;
            case R.id.spare:
                list.setAdapter(spareAdapter);
                break;
            case R.id.massive_test:
                list.setAdapter(massiveTestAdapter);
                break;
        }
        list.setState(State.INIT_REFRESHING, true);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        switch (lastCheckedId) {
            case R.id.attentions:
                getActionItems(0);
                break;
            case R.id.spare:
                getSpareItems(0);
                break;
            case R.id.massive_test:
                getTestItems(0);
                break;
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        switch (lastCheckedId) {
            case R.id.attentions:
                getActionItems(currentActionPage + 1);
                break;
            case R.id.spare:
                getSpareItems(currentSparePage + 1);
                break;
            case R.id.massive_test:
                getTestItems(currentMassivePage + 1);
                break;
        }
    }

    private void getTestItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "user_topic");
        params.put("other_user_id", userId);
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryListResponse.class, true, params, new Listener<DiscoveryListResponse>() {
            @Override
            public void onResponse(DiscoveryListResponse response) {
                if (response.isSuccess()) {
                    if (page == 0) {
                        massiveTestItems.clear();
                    }
                    Collections.addAll(massiveTestItems, response.data);
                    massiveTestAdapter.notifyDataSetChanged();
                    currentMassivePage = response.page;
                } else {
                    Utils.showToast(response.msg);
                }
                refreshComplete();
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private void getSpareItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "user_goods");
        params.put("other_user_id", userId);
        GsonRequest<SpareListResponse> request = new GsonRequest<>(url, Method.POST,
                SpareListResponse.class, true, params, new Listener<SpareListResponse>() {
            @Override
            public void onResponse(SpareListResponse response) {
                if (response.isSuccess()) {
                    if (page == 0) {
                        spareItems.clear();
                    }
                    Collections.addAll(spareItems, response.data);
                    spareAdapter.notifyDataSetChanged();
                    currentSparePage = response.page;
                } else {
                    Utils.showToast(response.msg);
                }
                refreshComplete();
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private void getActionItems(final int page) {
        String url = NetworkConstants.MEMBER_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        params.put("act", "other_favorite");
        params.put("other_user_id", userId);
        GsonRequest<ActionListResponse> request = new GsonRequest<>(url, Method.POST,
                ActionListResponse.class, true, params, new Listener<ActionListResponse>() {
            @Override
            public void onResponse(ActionListResponse response) {
                if (response.isSuccess()) {
                    if (page == 0) {
                        actions.clear();
                    }
                    Collections.addAll(actions, response.data);
                    actionAdapter.notifyDataSetChanged();
                    currentActionPage = response.page;
                    headerViewHolder.sign.setText(response.yijuhua);
                } else {
                    Utils.showToast(response.msg);
                }
                refreshComplete();
            }
        }, mErrorListener);
        mQueue.add(request);
//        mQueue.start();
    }

    private void refreshComplete() {
        list.postDelayed(new Runnable() {
            @Override
            public void run() {
                list.onRefreshComplete();
            }
        }, 100);
    }

    /**
     * This class contains all butterknife-injected Views & Layouts from layout file
     * 'user_profile_header_view.xml'
     * for easy to all layout elements.
     *
     * @author ButterKnifeZelezny, plugin for Android Studio by Avast Developers
     *         (http://github.com/avast)
     */
    static class UserProfileHeaderViewHolder {

        @InjectView(R.id.avatar)
        RoundedImageView avatar;

        @InjectView(R.id.name)
        TextView name;

        @InjectView(R.id.sign)
        TextView sign;

        @InjectView(R.id.private_msg)
        TextView privateMsg;

        @InjectView(R.id.attentions)
        View attentions;

        @InjectView(R.id.massive_test)
        View massiveTest;

        @InjectView(R.id.spare)
        View spare;


        UserProfileHeaderViewHolder(View view) {
            ButterKnife.inject(this, view);
        }
    }

    private List<DiscoveryItem> massiveTestItems = new ArrayList<>();

    private class MassiveTestAdapter extends BaseAdapter {

        @Override
        public int getCount() {

            return massiveTestItems.isEmpty() ? 1 : massiveTestItems.size();
        }

        @Override
        public DiscoveryItem getItem(int position) {
            return massiveTestItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LogUtils.d("getView, massiveTestItems size is " + massiveTestItems.size() + ", position is " + position);
            if (massiveTestItems.isEmpty()) {
                TextView textView = (TextView) getLayoutInflater().inflate(R.layout
                        .profile_empty_view, parent, false);
                textView.setText(R.string.ta_no_test);
                return textView;
            }
            DiscoveryViewHolder holder;
            View view = convertView;
            LogUtils.d("view is null? " + (view == null) + ", position is " + position);
            if (view == null || view.getTag() == null) {
                view = getLayoutInflater()
                        .inflate(R.layout.discovery_list_item, parent, false);
                holder = new DiscoveryViewHolder(view, UserProfileActivity.this,
                        DiscoveryViewHolder.TYPE_MASSIVE_TEST);
                view.setTag(holder);
            }
            holder = (DiscoveryViewHolder) view.getTag();
            DiscoveryItem item = getItem(position);
            holder.bindDiscoveryItem(item);
            return view;
        }
    }

    private MassiveTestAdapter massiveTestAdapter;

    private List<SpareItem> spareItems = new ArrayList<>();

    private class SpareAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return spareItems.isEmpty() ? 1 : spareItems.size();
        }

        @Override
        public SpareItem getItem(int position) {
            return spareItems.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            SpareItemViewHolder holder;
            View view = convertView;
            if (spareItems.isEmpty()) {
                TextView textView = (TextView) getLayoutInflater().inflate(R.layout
                        .profile_empty_view, parent, false);
                textView.setText(R.string.ta_no_spare);
                return textView;
            }
            if (view == null || view.getTag() == null) {
                view = getLayoutInflater()
                        .inflate(R.layout.spare_list_item, parent, false);
                holder = new SpareItemViewHolder(view, UserProfileActivity.this);
                view.setTag(holder);
            }
            holder = (SpareItemViewHolder) view.getTag();
            SpareItem item = getItem(position);
            holder.bindItem(item, false, false);
            return view;
        }
    }

    private SpareAdapter spareAdapter;

    List<Action> actions = new ArrayList<>();

    private class ActionAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return actions.isEmpty() ? 1 : actions.size();
        }

        @Override
        public Action getItem(int position) {
            return actions.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (actions.isEmpty()) {
                TextView textView = (TextView) getLayoutInflater().inflate(R.layout
                        .profile_empty_view, parent, false);
                textView.setText(R.string.ta_no_att);
                return textView;
            }
            final Action action = getItem(position);
            LogUtils.d("action is " + action);
            if (view == null || view.getTag() == null) {
                view = getLayoutInflater().inflate(R.layout.attention_list_item, parent, false);
                view.setTag(action);
            }
            TextView time = (TextView) view.findViewById(R.id.time);
            time.setText(DateUtils.getRelativeTimeSpanString(action.favorite_time * 1000, System
                            .currentTimeMillis(), DateUtils.MINUTE_IN_MILLIS,
                    DateUtils.FORMAT_ABBREV_RELATIVE
            ));
            TextView name = (TextView) view.findViewById(R.id.name);
            name.setText(action.getName());
            TextView title = (TextView) view.findViewById(R.id.title);
            title.setText(action.title);
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (action.isMassiveTest()) {
                        Intent intent = new Intent(UserProfileActivity.this,
                                DiscoveryDetailActivity.class);
                        DiscoveryItem item = new DiscoveryItem();
                        item.id = Integer.parseInt(action.id);
                        item.name = action.title;
                        intent.putExtra(Constants.MASSIVE_TEST_ITEM_KEY, item.toString());
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent(UserProfileActivity.this, SpareDetailActivity.class);
                        SpareItem item = new SpareItem();
                        item.user_goods_id = action.id;
                        item.name = action.title;
                        intent.putExtra(Constants.DISCOVERY_ITEM_KEY, item.toString());
                        startActivity(intent);
                    }
                }
            });
            return view;
        }
    }

    private ActionAdapter actionAdapter;

    private void bindUserInfo() {
        ImageLoader.getInstance()
                .displayImage(avatar, headerViewHolder.avatar, ImageUtils.getAvatarDisplayOption());
        headerViewHolder.name.setText(username);
    }

    protected ErrorListener mErrorListener = new ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dismissProgress();
            Throwable t = error.getCause();
            if (t instanceof ErrorResponseException) {
                Utils.showToast(error.getMessage());
            } else {
                Utils.showToast(R.string.generic_failure);
            }
            refreshComplete();
        }
    };
}
